<template>
    <div class="employee-container">
      <el-table 
        :data="staffStore.staffList" 
        border 
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold' }"
        row-key="id"
      >
        <el-table-column 
          prop="id" 
          label="序号" 
          width="80" 
          align="center"
        />
        <el-table-column 
          prop="name" 
          label="员工姓名" 
          width="120"
        />
        <el-table-column 
          prop="phone" 
          label="联系电话" 
          width="150"
        />
        <el-table-column 
          prop="address" 
          label="员工住址" 
          min-width="160"
          show-overflow-tooltip
        />
        <el-table-column 
          label="属性" 
          width="220"
        >
          <template #default="{ row }">
            <div class="service-tags">
              <el-tag 
                v-for="(service, index) in row.services" 
                :key="index"
                class="mr-2 mb-2"
              >
                {{ service }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column 
          prop="rank" 
          label="员工等级" 
          width="150"
          align="center"
        >
          <template #default="{ row }">
            <span
              :class="{
                'gold-rank': row.rank === '金牌员工',
                'silver-rank': row.rank === '银牌员工',
                'bronze-rank': row.rank === '铜牌员工'
              }"
            >
              {{ row.rank }}
            </span>
          </template>
        </el-table-column>
        <el-table-column 
          prop="workPeriod" 
          label="工作周期" 
          width="130"
          align="center"
        >
          <template #default="{ row }">
            <div class="work-period">
              <div 
                v-for="(period, index) in row.workPeriods" 
                :key="index"
                class="period-item"
              >
                {{ period }} 
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column 
          prop="salary" 
          label="薪资/月" 
          width="150"
          align="center"
        />
        <el-table-column 
          label="操作" 
          width="290"
          align="center"
        >
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                @click="handleEdit(row)"
              >
                修改
              </el-button>
              <el-button 
                type="danger" 
                @click="handleDelete(row.id)"
              >
                删除
              </el-button>
              <el-button 
                :type="row.status ? 'warning' : 'success'" 
                @click="toggleStatus(row)"
              >
                {{ row.status ? '暂停接单' : '开启接单' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table> 
      <CreateStaff ref="createStaffRef" />
    </div>
  </template>
  
<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CreateStaff from '@/components/CreateStaff.vue'
import instance from '@/api'
import { emitter } from '@/utils/emitter'
import { useStaffStore } from '@/stores/useStaffStore'

const staffStore = useStaffStore()
const createStaffRef = ref()

const handleEdit = (row: any) => {
  createStaffRef.value.openEdit(row)
}

const handleEditSuccess = (e: any) => {
  const updatedStaff = e.detail
  const idx = staffStore.staffList.findIndex((item: any) => item.id === updatedStaff.id)
  if (idx !== -1) {
    staffStore.staffList.splice(idx, 1, { ...updatedStaff })
    staffStore.updateAvailableStaffList()
  }
}

// 监听新增员工事件
const handleStaffAdded = (newStaff: any) => {
  staffStore.staffList.push(newStaff)
  staffStore.updateAvailableStaffList()
}

const handleDelete = (id: number) => {
  ElMessageBox.confirm('确定要删除该员工记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const resp = await instance.delete(`/api/staff/deleteStaff/${id}`)
    if (resp.status === 200) {
      const index = staffStore.staffList.findIndex((item: { id: number }) => item.id === id)
      if (index !== -1) {
        staffStore.staffList.splice(index, 1)
        staffStore.updateAvailableStaffList()
        ElMessage.success('删除成功')
      }
    } else {
      ElMessage.error('删除失败')
    } 
  })
}

const toggleStatus = async (row: any) => {
  try {
    const newStatus = !row.status
    const resp = await instance.put(`/api/staff/updateStaffStatus/${row.id}`, null, {
      params: {
        status: newStatus ? 1 : 0
      }
    })
    if (resp.status === 200) {
      staffStore.updateStaffStatus(row.id, newStatus)
      ElMessage.success(`已${newStatus ? '开启' : '暂停'}接单状态`)
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

onMounted(async() => {
  await staffStore.fetchStaffList()
  // 添加事件监听
  emitter.on('staff-added', handleStaffAdded)
  window.addEventListener('edit-success', handleEditSuccess)
})

// 组件卸载前移除事件监听
onBeforeUnmount(() => {
  emitter.off('staff-added', handleStaffAdded)
  window.removeEventListener('edit-success', handleEditSuccess)
})
</script>
  
<style scoped>
  .employee-container {
    padding: 20px;
    background: #fff;
  }
  
  .service-tags {
    display: flex;
    flex-wrap: wrap;
  }
  
  .work-period {
    line-height: 1.5;
  }
  
  .period-item {
    margin: 2px 0;
    margin-right: 5px;
    display: inline-block;
  }
  
  .mr-2 {
    margin-right: 0.5rem;
  }
  
  .mb-2 {
    margin-bottom: 0.5rem;
  }
  
  .el-table {
    margin-top: 20px;
  }
  
  .el-table--border {
    border: 1px solid #ebeef5;
  }
  
  .gold-rank {
    color: #FFD700;
    font-weight: bold;
  }
  .silver-rank {
    color: #C0C0C0;
    font-weight: bold;
  }
  .bronze-rank {
    color: #CD7F32;
    font-weight: bold;
  }
  
  .action-buttons {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    gap: 10px;
  }
</style>